package com.helen.ui.applymerchent;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.coorchice.library.SuperTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.db.UserHelper;
import com.helen.entity.AddressListEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.applymerchent.entity.AddNewRecoveryEntity;
import com.helen.utils.KeybordUtils;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.MyEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/4/26.
 * 新增地址
 */

public class AddNewRecoveryAddressActivity extends BaseActivity {

    @BindView(R.id.et_name)
    MyEditText etName;
    @BindView(R.id.et_contact)
    MyEditText etContact;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.ll_select_location)
    LinearLayout llSelectLocation;
    @BindView(R.id.et_detail_address)
    MyEditText etDetailAddress;
    @BindView(R.id.cb)
    CheckBox cb;
    @BindView(R.id.tv_save)
    SuperTextView tvSave;
    private AddressListEntity addressListEntity;
    private String address;
    private int provinceId = 0;
    private int cityId = 0;
    private int areaId = 0;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_add_new_address;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        addressListEntity = (AddressListEntity) getIntent().getSerializableExtra("addressListEntity");
        if (addressListEntity != null) {
            getToolbarTitle().setText(R.string.edit_recovery_address);
            etName.setText(addressListEntity.getName());
            etName.setSelection(etName.getText().toString().length());
            etContact.setText(addressListEntity.getPhone());
            tvLocation.setText(addressListEntity.getCityName());
            etDetailAddress.setText(addressListEntity.getDetail());
            cb.setChecked(addressListEntity.getIsDefault().equals("true") ? true : false);
        } else {
            getToolbarTitle().setText(R.string.new_address);
        }

    }

    @Override
    protected void updateViews() {

    }

    private void addAddressApi(String name, String phone, String detail, String isDefault) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        if (addressListEntity != null) {
            params.put("id", addressListEntity.getId());
        }else {
            params.put("id", "0");
        }
        params.put("userid", UserHelper.getInstance().getloginEntity(AddNewRecoveryAddressActivity.this).getId() + "");
        params.put("name", name);
        params.put("phone", phone);
        if(areaId!=0){
            params.put("cityId", areaId+"");
        }else if(cityId!=0){
            params.put("cityId", cityId+"");
        }else if(provinceId!=0){
            params.put("cityId", provinceId+"");
        }
        params.put("detail", detail);
        params.put("isDefault", isDefault);
        EasyHttp.post(Constants.SAVEAGENTADDRESS)
                .baseUrl(Constants.APP_API_BASE2)
                .params(params)
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "新增地址失败==" + e.toString());
                        MToast.makeTextShort(AddNewRecoveryAddressActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(AddNewRecoveryAddressActivity.this, result, TAG);
                        if (data != null) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }
                });
    }

    private ArrayList<AddNewRecoveryEntity> addNewRecoveryEntityList = new ArrayList<>();

    private void AgentCityListApi() {
        mMProgressDialog.show();
        EasyHttp.post(Constants.AGENTCITYLIST)
                .baseUrl(Constants.APP_API_BASE2)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onSuccess(String s) {
                        MyLog.d("yang", "s==" + s);
                        mMProgressDialog.dismiss();
                        String data = PhoneUtils.checkResponseFlag2(AddNewRecoveryAddressActivity.this, s, TAG);
                        if (data != null && !data.equals("[]")) {
                            addNewRecoveryEntityList = new Gson().fromJson(data, new TypeToken<ArrayList<AddNewRecoveryEntity>>() {
                            }.getType());
                            showPickerView(addNewRecoveryEntityList);
                        }
                    }
                });

    }

    private ArrayList<AddNewRecoveryEntity> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<AddNewRecoveryEntity.SubBeanX>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<AddNewRecoveryEntity.SubBeanX.SubBean>>> options3Items = new ArrayList<>();

    private void showPickerView(ArrayList<AddNewRecoveryEntity> jsonBean) {// 弹出选择器
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<AddNewRecoveryEntity.SubBeanX> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<AddNewRecoveryEntity.SubBeanX.SubBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            if (jsonBean.get(i).getSub() != null && jsonBean.get(i).getSub().size() > 0) {
                for (int c = 0; c < jsonBean.get(i).getSub().size(); c++) {//遍历该省份的所有城市
                    String CityName = jsonBean.get(i).getSub().get(c).getName();
                    int CityId = jsonBean.get(i).getSub().get(c).getId();
                    CityList.add(new AddNewRecoveryEntity.SubBeanX(CityId, CityName));//添加城市
                    ArrayList<AddNewRecoveryEntity.SubBeanX.SubBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                    if (jsonBean.get(i).getSub().get(c) != null) {
                        if (jsonBean.get(i).getSub().get(c).getSub() != null && jsonBean.get(i).getSub().get(c).getSub().size() > 0) {
                            City_AreaList.addAll(jsonBean.get(i).getSub().get(c).getSub());
                        } else {
                            City_AreaList.add(new AddNewRecoveryEntity.SubBeanX.SubBean(0, ""));
                        }
                    } else {
                        City_AreaList.add(new AddNewRecoveryEntity.SubBeanX.SubBean(0, ""));
                    }
                    Province_AreaList.add(City_AreaList);//添加该省所有地区数据

                }
            } else {
                CityList.add(new AddNewRecoveryEntity.SubBeanX(0, ""));//添加城市
                ArrayList<AddNewRecoveryEntity.SubBeanX.SubBean> City_AreaList2 = new ArrayList<>();//该城市的所有地区列表
                City_AreaList2.add(new AddNewRecoveryEntity.SubBeanX.SubBean(0, ""));
                Province_AreaList.add(City_AreaList2);//添加该省所有地区数据
            }


            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }


        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                address = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2).getPickerViewText() +
                        options3Items.get(options1).get(options2).get(options3).getPickerViewText();
                provinceId =  options1Items.get(options1).getId();
                cityId = options2Items.get(options1).get(options2).getId();
                areaId = options3Items.get(options1).get(options2).get(options3).getId();
                tvLocation.setText(address);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    @OnClick({R.id.ll_select_location, R.id.cb, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_location:
                if (KeybordUtils.isSoftShowing(AddNewRecoveryAddressActivity.this)) {
                    KeybordUtils.closeKeybord(etContact, AddNewRecoveryAddressActivity.this);
                }
                AgentCityListApi();
                break;
            case R.id.cb:
                break;
            case R.id.tv_save:
                String name = etName.getText().toString().trim();
                String phone = etContact.getText().toString().trim();
                String city = tvLocation.getText().toString().trim();
                String detail = etDetailAddress.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    MToast.makeTextLong(AddNewRecoveryAddressActivity.this, "姓名不能为空").show();
                    etName.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    MToast.makeTextLong(AddNewRecoveryAddressActivity.this, "联系方式不能为空").show();
                    etContact.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(city)) {
                    MToast.makeTextLong(AddNewRecoveryAddressActivity.this, "地区不能为空").show();
                    return;
                }
                if (TextUtils.isEmpty(detail)) {
                    MToast.makeTextLong(AddNewRecoveryAddressActivity.this, "详细地址不能为空").show();
                    etDetailAddress.requestFocus();
                    return;
                }
                addAddressApi(name, phone,  detail, cb.isChecked() ? "true" : "false");
                break;
        }
    }


}
